import numpy as np
from math import sqrt


# 计算两个城市之间的距离
def distance(city1, city2):
    x1, y1 = city1
    x2, y2 = city2
    return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)


# 计算路径总长度
def total_distance(path, cities):
    total = 0.0
    num_cities = len(path)

    for i in range(num_cities):
        from_city = cities[path[i]]
        to_city = cities[path[(i + 1) % num_cities]]
        total += distance(from_city, to_city)

    return total


# 计算适应度
def calculate_fitness(population, cities):
    fitness_values = []
    for individual in population:
        dist = total_distance(individual, cities)
        fitness_values.append(1 / (dist + 1e-10))
    return np.array(fitness_values)
